import { OrderState as ESource, OrderState as EOrderState } from '@/types';
import { defaults } from 'lodash-es';
export { ESource as EBomSource, EOrderState };
export { IListParams as IBomListParams };

interface IListParams {
  source?: ESource;
  orderState?: EOrderState;
  pageNum?: number;
  pageSize?: number;
}
async function getOriginList(params?: IListParams) {
  const { source, orderState, pageNum, pageSize } = defaults(params, {
    pageNum: 1,
    pageSize: 10,
  });
  // 获取板件数据
  const res = await Manycore.Integration.FOP.findOrdersAsync({
    // orderState: source,
    orderState,
    start: (pageNum - 1) * pageSize,
    num: pageSize,
  });
  const orders = res.result;
  const { totalCount: total, hasMore } = res;
  // console.log({ orders });
  const promises = orders.map(async (order) => {
    const { orderId } = order;
    const plankList = (
      await Manycore.Integration.Bom.getPlankListAsync({ orderId })
    ).result;
    // console.log({ orderId, plankList });
    return { order, plankList, total };
  });
  const data = await Promise.all(promises);
  return { data, total, hasMore };
}

async function getList(params: IListParams) {
  const res = await getOriginList(params);
  const { data: list, total, hasMore } = res;
  // console.log({ results });
  const data = list.map((item) => {
    const { order: order_2, plankList: plankList_1, total } = item;
    return {
      id: order_2.orderId,
      name: order_2.orderName,
      date: order_2.placeTime,
      data: plankList_1,
    };
  });
  return { data, total, hasMore };
}

async function getMergePlankList(params: IListParams) {
  const { pageNum, pageSize } = defaults(params, {
    pageNum: 1,
    pageSize: 10,
  });

  // 获取合批数据
  const res = await Manycore.Integration.FOP.findMergeTasksAsync({
    start: (pageNum - 1) * pageSize,
    num: pageSize,
  });
  const merges = res.result;
  const { totalCount: total, hasMore } = res;
  const promises = merges.map(async (merge) => {
    const { mergeId } = merge;
    const plankList = (
      await Manycore.Integration.Bom.getPlankListAsync({
        // @ts-ignore
        mergeIds: [mergeId].join(),
      })
    ).result;
    return { merge, plankList, total };
  });
  const data = await Promise.all(promises);

  const list = data.map((item) => {
    return {
      id: item.merge.mergeId,
      name: item.merge.mergeName,
      date: 0,
      data: item.plankList,
    };
  });

  return { data: list, total, hasMore };
}

export interface IPlankListParams {
  orderId?: string;
  mergeId?: string;
}
const getPlankList = async (params: IPlankListParams) => {
  const { mergeId, orderId } = params;

  return await Manycore.Integration.Bom.getPlankListAsync({
    // @ts-ignore
    orderId,
    // @ts-ignore
    mergeIds: mergeId,
  });
};

export const bomApi = { list: getList, getMergePlankList, getPlankList };
